import java.io.BufferedInputStream;
import java.io.IOException;

public class NetChunkUtil {
    //调用一次recive函数,接收一个完整的块(一个块的具体是一个byte[]数组)
    static byte[] recive(BufferedInputStream bis){
        byte[] head = new byte[4];
        try {
            if(bis.read(head)==-1)//读入包头,即一个整数int
                return null;
            int bolckLength = byteArrayToInt(head);

            System.out.println("块大小:"+bolckLength);
            //接收流的代码
            int unReadByteNum = bolckLength;//此块剩余未读的byte个数
            int nowReadByteNum = 0;//本轮循环读取的byte个数
            int bufferPos = 0;//当前buffer读取的下标
            byte[] buffer = new byte[bolckLength];
            byte[] buffer_temp = new byte[1024];
            byte[] buffer_temp_dymanic = null;
            while (true){//这里是死循环,要记得设置超时!!!否则发送方断线,会造成僵尸线程,僵尸连接
                if(unReadByteNum==0){
                    break;
                }
                if(unReadByteNum < buffer_temp.length){
                    buffer_temp_dymanic = new byte[unReadByteNum];
                    nowReadByteNum = bis.read(buffer_temp_dymanic);
                    System.arraycopy(buffer_temp_dymanic, 0, buffer, bufferPos, nowReadByteNum);
                }else {
                    nowReadByteNum = bis.read(buffer_temp);
                    System.arraycopy(buffer_temp, 0, buffer, bufferPos, nowReadByteNum);
                }
                unReadByteNum = unReadByteNum - nowReadByteNum;
                bufferPos += nowReadByteNum;

            }
            return buffer;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    static int byteArrayToInt(byte[] bytes){
        int b0 = bytes[0] & 0xFF;
        int b1 = bytes[1] & 0xFF;
        int b2 = bytes[2] & 0xFF;
        int b3 = bytes[3] & 0xFF;
        return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
    }
    static byte[] intToByteArray(int num){
        byte[] bytes = new byte[4];
        bytes[0] = (byte)(num >> 24 & 0xFF);//0xFF即"最低8位,连续8个1",一个16进制4个bit
        bytes[1] = (byte)(num >> 16 & 0xFF);
        bytes[2] = (byte)(num >> 8 & 0xFF);
        bytes[3] = (byte)(num & 0xFF);
        return bytes;
    }
}
